package fr.miage.dao;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException;

import fr.miage.connexion.ConnexionBD;
import fr.miage.model.User;

public class UserDAO{
	
	private Logger logger = Logger.getRootLogger();
	
	public User getById(String id) {		
		ResultSet res = null;
		String query = "select * from user WHERE idUser="+id;
		Statement st = null;
		User user = null;
		try {
			st = ConnexionBD.getInstance().getConn().createStatement();
			res = st.executeQuery(query);
			if(res.next()){
				user = getUser(res);
			}else{
				return null;
			}
		} catch (SQLException ex) {
			logger.error(ex);
		} finally {
			try {
				if (res != null) {
					res.close();
				}
				if (st != null) {
					st.close();
				}
			} catch (SQLException e) {
				logger.error(e);
			}
		}
		
		return user;
	}
	
	private User getUser(ResultSet res){
		User user = new User();
		try {
			user.setFirstName(res.getString("firstName"));
			user.setIdAdress(res.getLong("idAdress"));
			user.setMail(res.getString("mail"));
			user.setName(res.getString("name"));
			user.setPhone(res.getString("phone"));
			user.setPwd(res.getString("pwd"));
		} catch (SQLException e) {
			logger.error(e);
			e.printStackTrace();
		}
		return user;
	}

	public int addUser(User user) {
		int res = 0;
		String pwdModif = user.getName()+user.getMail()+user.getPhone()+user.getPwd();
		String salt = ConnexionBD.getInstance().getSalt();
		pwdModif += salt;
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(pwdModif.getBytes());
			byte[] digest = md.digest();
			//convert the byte to hex format method 1
	        StringBuffer sb = new StringBuffer();
	        for (int i = 0; i < digest.length; i++) {
	          sb.append(Integer.toString((digest[i] & 0xff) + 0x100, 16).substring(1));
	        } 
	        user.setPwd(sb.toString());
		} catch (NoSuchAlgorithmException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		String query = "insert into user(name, firstName, mail, pwd, phone, idAdress) values ('"+user.getName()+"', '"+user.getFirstName()+"', '"+user.getMail()+"', '"+user.getPwd()+"','"+user.getPhone()+"', "+user.getIdAdress()+")";
		Statement st = null;
		try {
			st = ConnexionBD.getInstance().getConn().createStatement();
			res = st.executeUpdate(query);
			return res;
		}catch(MySQLIntegrityConstraintViolationException e){
			logger.error(e);
			e.printStackTrace();
			return -1;
		}catch (SQLException ex) {
			logger.error(ex);
			ex.printStackTrace();
			return res;
		} finally {
			try {
				if (st != null) {
					st.close();
				}
			} catch (SQLException e) {
				logger.error(e);
				e.printStackTrace();
			}
		}
	}

	public int deleteUser(String id) {
		int res = 0;
		String query = "delete from user where idUser="+id;
		Statement st = null;
		try {
			st = ConnexionBD.getInstance().getConn().createStatement();
			res = st.executeUpdate(query);
			return res;
		} catch (SQLException ex) {
			logger.error(ex);
			ex.printStackTrace();
			return res;
		} finally {
			try {
				if (st != null) {
					st.close();
				}
			} catch (SQLException e) {
				logger.error(e);
				e.printStackTrace();
			}
		}
	}

	public List<User> getAllUserByEvent(String idEvent) {
		ResultSet res = null;
		String query = "select * from invitation i inner join user u on i.idUser = u.idUser WHERE idEvent="+idEvent;
		Statement st = null;
		List<User> listeUser = null;
		try {
			st = ConnexionBD.getInstance().getConn().createStatement();
			res = st.executeQuery(query);
			listeUser = new ArrayList<User>();
			while(res.next()){
				User user = getUser(res);
				listeUser.add(user);
			}
		} catch (SQLException ex) {
			logger.error(ex);
		} finally {
			try {
				if (res != null) {
					res.close();
				}
				if (st != null) {
					st.close();
				}
			} catch (SQLException e) {
				logger.error(e);
			}
		}
		
		return listeUser;
	}
}
